import { ref, onBeforeUnmount } from 'vue'

export const useCountdown = () => {
	let timer: any

	const countdown = ref(0)

	const onTimer = () => {
		countdown.value = countdown.value - 1
		if (countdown.value > 0) {
			timer = setTimeout(() => onTimer(), 1000)
		}
	}

	const reset = (val: number) => {
		timer && clearTimeout(timer)
		countdown.value = val
		if (val > 0) {
			timer = setTimeout(() => onTimer(), 1000)
		}
	}

	onBeforeUnmount(() => timer && clearTimeout(timer))

	return { countdown, reset }
}
